package com.ant.backstage.validated;

import com.ant.backstage.facade.exception.ValidatedException;
import org.hibernate.validator.HibernateValidator;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import java.util.Set;

/**
 * @Author zhangyu
 * @Description
 * * JSR303 Validator(Hibernate Validator)工具类.
 *  * ConstraintViolation中包含propertyPath, msg 和invalidValue等信息.
 *  * 提供了各种convert方法，适合不同的i18n需求:
 *  * 1. List<String>, String内容为message
 * @Date 17:43 2021/12/27
 * @Param  为避免springboot 循环注入，这个utils只能在web
 * @return 
 **/
public class ValidationUtils {

    /**
     * 使用hibernate的注解来进行验证
     */
    private static final Validator validator = Validation.byProvider(HibernateValidator.class)
            .configure().failFast(true).buildValidatorFactory().getValidator();

    public static<T> Boolean validate(T v){
        Set<ConstraintViolation<T>> set= validator.validate(v);
        return set.size() == 0;
    }

    public static void validData(BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            StringBuilder sb = new StringBuilder();
            for (ObjectError error : bindingResult.getAllErrors()) {
                sb.append(error.getDefaultMessage());
            }
            throw new ValidatedException(sb.toString(), "1000");
        }
    }
//    /**
//     * 功能描述: <br>
//     * 〈注解验证参数〉
//     * @param object
//     */
//    public static <T> void validate(T object) {
//        if (object != null){
//            Set<ConstraintViolation<T>> constraintViolations = validator.validate(object);
//            if (CollectionUtils.isNotEmpty(constraintViolations)) {
//                String msg = "参数错误" + ":" + constraintViolations.iterator().next().getMessage();
//
//            }
//        }
//    }
}
